package me.acomma.groot.domain.menu;

import me.acomma.groot.infrastructure.dao.MenuDao;
import me.acomma.groot.infrastructure.id.ID;
import me.acomma.groot.domain.role.RoleId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Repository
public class MenuRepository {
    @Autowired
    private MenuDao menuDao;

    public MenuId nextId() {
        return new MenuId(ID.next());
    }

    public void add(Menu menu) {
        menuDao.insert(menu);
    }

    public Menu get(MenuId menuId) {
        return menuDao.select(menuId);
    }

    public void update(Menu menu) {
        menuDao.update(menu);
    }

    public void remove(Menu menu) {
        menuDao.delete(menu.getMenuId());
    }

    public long countByParentId(MenuId menuId) {
        return menuDao.countByParentId(menuId);
    }

    public List<Menu> all() {
        return menuDao.selectAll();
    }

    public long countByRoleId(RoleId roleId) {
        if (roleId == null) {
            return 0;
        }
        List<Menu> menus = menuDao.selectByRoleId(roleId);
        return CollectionUtils.isEmpty(menus) ? 0 : menus.size();
    }

    public List<Menu> getByRoleId(RoleId roleId) {
        return menuDao.selectByRoleId(roleId);
    }
}
